package com.base.util;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

public class PlayHelper {
    private MediaPlayer mediaPlayer;
    private static volatile PlayHelper mInstance;
    private AudioDurationCallback callback;
    private VideoOrTtsPlayCallback videoOrTtsPlayCallback;

    private PlayHelper() {
    }

    public static PlayHelper getInstance() {
        if (mInstance == null) {
            synchronized (PlayHelper.class) {
                if (mInstance == null)
                    mInstance = new PlayHelper();
            }
        }
        return mInstance;
    }

    public void setAudioDurationCallback(AudioDurationCallback callback) {
        this.callback = callback;
    }

    /**
     * 需要在play之前调用，否则play时，callback 是NULL
     */
    public void setVideoOrTtsPlayCallback(VideoOrTtsPlayCallback callback) {
        this.videoOrTtsPlayCallback = callback;
    }

    public void play(Context context, int resId) {
        try {
            if (null != mediaPlayer) {
                mediaPlayer.reset();
            }
            release();
            mediaPlayer = MediaPlayer.create(context.getApplicationContext(), resId);
            initPlayListener();
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initPlayListener() {
        if (null == mediaPlayer)
            return;
        //视频/音频源准备好=>回调
        mediaPlayer.setOnPreparedListener(mediaPlayer -> {
            //mediaPlayer.start();
            //Log.e("play", "onPrepared: ");
            if (null != videoOrTtsPlayCallback)
                videoOrTtsPlayCallback.onPrepared(mediaPlayer);
        });
        //seekTo操作完成后的回调
        mediaPlayer.setOnSeekCompleteListener(mp -> {
            if (null != videoOrTtsPlayCallback)
                videoOrTtsPlayCallback.onSeekComplete(mp);
        });
        //播放完成=>回调
        mediaPlayer.setOnCompletionListener(mediaPlayer -> {
            if (null != videoOrTtsPlayCallback)
                videoOrTtsPlayCallback.onCompletion(mediaPlayer);
            release();
        });
        //播放过程中出现错误=>回调
        mediaPlayer.setOnErrorListener((mediaPlayer, what, extra) -> {
            boolean errorInPlaying = false;
            if (null != videoOrTtsPlayCallback)
                errorInPlaying = videoOrTtsPlayCallback.onError(mediaPlayer, what, extra);
            //Log.e("play", "sound onError: " + what + ", " + extra);
            return errorInPlaying;
        });
    }

    public void playFromUri(Context context, Uri uri) {
        playFromUri(context, uri, mp -> {
            release();
            //Log.e("play", "onCompletion: play sound.");
        });
    }

    public void playFromUri(Context context, Uri uri, MediaPlayer.OnCompletionListener completionListener) {
        if (null == uri)
            return;
        try {
            if (null != mediaPlayer) {
                mediaPlayer.reset();
            }
            release();
            mediaPlayer = MediaPlayer.create(context.getApplicationContext(), uri);
            int duration = mediaPlayer.getDuration();
            //int position = mediaPlayer.getCurrentPosition();
            if (null != callback)
                callback.onCallback(duration / 1000);
            mediaPlayer.setOnPreparedListener(mediaPlayer -> {
                //mediaPlayer.start();
            });
            mediaPlayer.setOnCompletionListener(completionListener);
            mediaPlayer.setOnErrorListener((mediaPlayer, what, extra) -> {
                //Log.e("play", "sound onError: " + what + ", " + extra);
                return false;
            });
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void release() {
        try {
            if (null == mediaPlayer)
                return;
            stop();
            mediaPlayer.release();
            mediaPlayer = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            if (null == mediaPlayer)
                return;
            if (isPlaying())
                mediaPlayer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isPlaying() {
        try {
            if (null == mediaPlayer)
                return false;
            return mediaPlayer.isPlaying();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public interface AudioDurationCallback {
        /**
         * if (0 != duration) {
         * //更新 seekbar 长度
         * seekbar.setMax(duration);
         * int s = duration / 1000;
         * //设置文件时长，单位 "分:秒" 格式
         * String total = s / 60 + ":" + s % 60;
         * }
         */
        /**
         * @param duration 音频时常
         */
        void onCallback(int duration);
    }

    public interface AudioPlayCallback {
        void onPrepared(MediaPlayer mp);

        void onCompletion(MediaPlayer mp);
    }
}
